/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * This file is part of retabel.
 *
 * Copyright (c) 2011 by individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution
 * for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.retabel.service.render.exporter;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import org.retabel.persistence.entity.document.ContentTypeEnum;
import org.retabel.persistence.entity.render.RenderedDocumentPart;
import org.retabel.persistence.entity.report.RenderingEngineEnum;
import org.retabel.service.render.RenderServiceException;
import org.retabel.service.render.exportable.ExportableDocumentPart;
import org.retabel.service.render.exportable.JasperReportsExportableDocumentPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.util.*;

/**
 * Class description.
 * <p/>
 * <h3>Extra-Info</h3>
 * Created: 21:45 16.10.11
 *
 * @author Peter Herber
 * @version 1.0
 */
public class JasperReportsRenderingEngine extends RenderingEngine {

    /** The Logger. */
    private static final Logger logger = LoggerFactory.getLogger(JasperReportsExportableDocumentPart.class);

    private final Set<ContentTypeEnum> supportedContentTypeList;

    private final Set<ContentTypeEnum> supportedConcatenationTypeList;

    public JasperReportsRenderingEngine() {
        supportedContentTypeList = new HashSet<>();
        supportedContentTypeList.add(ContentTypeEnum.PDF);
        supportedContentTypeList.add(ContentTypeEnum.RTF);
        supportedContentTypeList.add(ContentTypeEnum.PRN);
        supportedConcatenationTypeList = new HashSet<>();
        supportedConcatenationTypeList.add(ContentTypeEnum.PDF);
        supportedConcatenationTypeList.add(ContentTypeEnum.RTF);
        supportedConcatenationTypeList.add(ContentTypeEnum.PRN);
    }

    @Override
    public Set<ContentTypeEnum> supportedContentTypes() {
        return Collections.unmodifiableSet(supportedContentTypeList);
    }

    @Override
    public Set<ContentTypeEnum> supportsConcatenationForContentTypes() {
        return Collections.unmodifiableSet(supportedConcatenationTypeList);
    }

    @Override
    public RenderedDocumentPart exportAndConcatenate(List<? extends ExportableDocumentPart> exportableDocumentParts,
                                       ContentTypeEnum contentType) throws RenderServiceException {

        List<JasperReportsExportableDocumentPart> jasperReportsExportableDocumentParts =
            (List<JasperReportsExportableDocumentPart>) exportableDocumentParts;

        List<JasperPrint> exportList = new LinkedList<>();
        for (JasperReportsExportableDocumentPart jasperReportsExportableDocumentPart : jasperReportsExportableDocumentParts)
        {
            if (!RenderingEngineEnum.JASPER_REPORTS.equals(jasperReportsExportableDocumentPart.getRenderingEngine()))
            {
                throw new RenderServiceException(
                    "exportable document has wrong rendering engine, expected: " + RenderingEngineEnum.JASPER_REPORTS + " found: "
                    + jasperReportsExportableDocumentPart.getRenderingEngine());
            }

            exportList.add(jasperReportsExportableDocumentPart.getRenderedContent());
        }

        try {
            JRExporter exporter;
            switch (contentType) {
                case PDF:
                    exporter = new JRPdfExporter();
                    break;
                case RTF:
                    exporter = new JRRtfExporter();
                    break;
                case PRN:
                    exporter = new JasperPrintExporter();
                    break;
                default:
                    throw new RenderServiceException("No export type for " + contentType + " found!");
            }

            exporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, exportList);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
            exporter.exportReport();

            byte[] contentData = baos.toByteArray();
            logger.debug("Content size: {}", contentData.length);

            RenderedDocumentPart documentPart = new RenderedDocumentPart();
            documentPart.setContent(contentData);
            documentPart.setContentType(contentType);

            return documentPart;
        } catch (JRException e) {
            throw new RenderServiceException(e.getMessage(), e);
        }
    }

}
